var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var app = getApp();
Page({
 data: {
  categoryList: [],
  currentCategory: {},
  currentSubCategoryList: {},
  scrollLeft: 0,
  scrollTop: 0,
  goodsCount: 0,
  scrollHeight: 0,
  userHasCollect: 0,
  amount:0,
  isShowSub:false,
  id: 0,
  cartList:[],
  buyCount:0
 },
 //跳转到购物车
  toCart: function(){
    wx.switchTab({
      url: '/pages/cart/cart',
    })
  },
  getList: function () {
    var that = this;
    util.request(api.ApiRootUrl + 'api/catalog/' + that.data.currentCategory.catId)
      .then(function (res) {
        that.setData({
          categoryList: res.data,
        });
      });
  },
  switchCate: function (event) {
    var that = this;
    var currentTarget = event.currentTarget;
    if (this.data.currentCategory.id == event.currentTarget.dataset.id) {
      return false;
    }

    this.getCurrentCategory(event.currentTarget.dataset.id);
  },
  //计算加入购物车的数量
  calintoCart(categoryList){
    var buycount = 0;
    if (categoryList == null || categoryList.length==0){
      return;
    }
    categoryList.forEach(function (obj) {
      buycount += obj.num;
    })
    return buycount;
  },
 //商品数量加url="/pages/category/category?id={{item.id}}"
 add(e){
   console.log('add++++')
   console.log(wx.getStorageSync('data'))
   console.log()
   var index=e.currentTarget.dataset.index;//每个商品的索引
   console.log(index);
   var id = e.currentTarget.dataset.id;//对象的id
   var categoryList = this.data.currentSubCategoryList;//所有商品
   console.log(this.data.cartList)
   var carts=this.data.cartList;//加入购物车内容
   console.log('carts');
   console.log(carts);
   var total = categoryList[index].brandId-0;//商品库存
   //验证库存
   if (total <= 0){
     wx.showToast({
       image: '/static/images/icon_error.png',
       title: '暂无商品',
     })
     return;
   }
   var num = categoryList[index].num-0;
   console.log('num1:'+num);
   //添加进购物车商品数量
   categoryList[index].num =num= num + 1 >= total ? total : num + 1;
   console.log('num2:' + categoryList[index].num);
     //1、如果数据不同就直接插入之前数据的前面，如果相同找到相同的然后直接替换
   console.log('id1：' +id);
   let isSame = carts.some(function (obj) {
       console.log('id2：' + obj.id);
       return obj.id == id;
     });
    let newIndex=carts.findIndex(function(obj){
      return obj.id == id; 
    })
    console.log("我发现你了，出来:"+newIndex)
   if(isSame && newIndex>=0){
     console.log("exist same something");
     carts.splice(newIndex, 1, categoryList[index]);
   }else{
     console.log("not exist same something");
     carts.splice(index, 0, categoryList[index]);
    //  carts.push(categoryList[index])
   }
   
   console.log("+++++++++++++")
   console.log(carts);
   console.log("+++++++++++++")
   if (num >=1) {
     categoryList[index].flag = true;
   } 
   var buycount=this.calintoCart(categoryList);
   this.setData({
     currentSubCategoryList: categoryList,
     cartList: carts,
     buyCount: buycount,
   })
   wx.setStorageSync('data', carts);
   //添加到购物车
  //  util.request(api.CartAdd, {
  //    goodsId: this.data.goods.id,
  //    number: this.data.number,
  //    productId: checkedProduct.id
  //  }, "POST")
  //    .then(function (res) {
  //      let _res = res;
  //      if (_res.errno == 0) {
  //        wx.showToast({
  //          title: '添加成功'
  //        });
  //      } else {
  //        wx.showToast({
  //          image: '/static/images/icon_error.png',
  //          title: _res.errmsg,
  //          mask: true
  //        });
  //      }

  //    });
 },
 //商品数量减
 sub(e){
   var t=this;
   var index = e.currentTarget.dataset.index;//数组的索引
   var id=e.currentTarget.dataset.id;//对象的id
   console.log('id:'+id);
   var categoryList = t.data.currentSubCategoryList;//所有商品
   var carts = t.data.cartList;//加入购物车内容
   var num = categoryList[index].num - 0;
   let newIndex = carts.findIndex(function (obj) {
     return obj.id == id;
   })
   if(num>1){
     categoryList[index].num=num = num - 1;
     carts.splice(newIndex, 1, categoryList[index]);
     console.log("--------------")
     console.log(index)
     console.log(carts);
     console.log("--------------")
   }else{
     categoryList[index].num = num = num - 1;
    // var search=carts.findIndex(function(obj){return obj.id==id});carts.splice(search, 1);
     console.log("00000000");
     carts=carts.filter(function(obj){
       console.log(obj);
        return obj.id !=id;
     });
    
     console.log(index);
     console.log(carts);
     console.log("000000000");
   }
   if(num==0){
     categoryList[index].flag = false;
   }
   //计算加入购物车的数量
   var buycount = this.calintoCart(categoryList);
   this.setData({
     currentSubCategoryList: categoryList,
     cartList:carts,
     buyCount: buycount,
   })
   wx.setStorageSync('data', carts);
 },
 toGoods(e){
   wx.navigateTo({
     url: '/pages/goods/goods?id=' + e.currentTarget.dataset.id + '&num=' + this.data.buyCount,
   })
 },
 //下拉刷新
 onPullDownRefresh() {
  wx.showNavigationBarLoading() //在标题栏中显示加载
  this.getCatalog();
  console.log('已下拉刷新')
  wx.hideNavigationBarLoading() //完成停止加载
  wx.stopPullDownRefresh() //停止下拉刷新
 },
 //刷新商品库存
 refreshShop:function(e){
   let that=this;
   let goodsList = this.data.currentSubCategoryList;
   console.log(goodsList.length == 0)
   if (goodsList.length == 0 || JSON.stringify(goodsList) == "{}") return;
   util.request(api.CatalogList).then(function (res) {
     
     let arr = res.data.currentSubCategory;
     goodsList.forEach(function(obj,index){
       obj.brandId=arr[index].brandId;
     });
     that.setData({
       currentSubCategoryList: goodsList,
     });
     console.log("刷新库存成功");
     console.log(that.data.currentSubCategoryList);
   });
 },
 //获取商品
 getCatalog: function() {
  //CatalogList
  let that = this;
  wx.showLoading({
   title: '加载中...',
  });
   wx.removeStorageSync('data');
  //  this.data.cartList
   console.log('data是否被删除')
  util.request(api.CatalogList).then(function(res) {
    console.log("----------------");
    console.log(res)
    console.log("----------------");
    let arr = res.data.currentSubCategory;
    for (let i = 0; i < arr.length ; i++){
      arr[i].num = 0;
      arr[i].flag=false;
      arr[i].checked=true;
    }
   that.setData({
    categoryList: res.data.categoryList,
    currentCategory: res.data.currentCategory,
    currentSubCategoryList: arr,
    buyCount:0,
    cartList: []
   });
   wx.hideLoading();
  });
  util.request(api.GoodsCount).then(function(res) {
   that.setData({
    goodsCount: res.data.goodsCount
   });
  });
 },
 getCurrentCategory: function(id) {
  let that = this;
  util.request(api.CatalogCurrent, {
    id: id
   })
   .then(function(res) {
     console.log("...........");
     console.log(res)
     console.log("............");
    that.setData({
     currentCategory: res.data.currentCategory,
     currentSubCategoryList: res.data.currentSubCategory
    });
   });
 },
 //从购物车返回的数据处理
 dealDataOfCart(){
   console.log("数据处理中。。。。。。")
   let sub = this.data.currentSubCategoryList;
   let cartlist = wx.getStorageSync('data');
   console.log(wx.getStorageSync('data'));
   console.log(cartlist);
   if(cartlist==null || cartlist.length==0){
     return;
   } 
   for (let i = 0; i < sub.length; i++) {
     let newIndex = cartlist.findIndex(function (obj) {
       return obj.id == sub[i].id;
     })  
       //0 2 1 3 4
       //0 1 2 3 4
       console.log("newIndex:"+newIndex);
       if(newIndex>=0){
         console.log("already exist data")
         sub[i].num = cartlist[newIndex].num;
        //  sub[i].brandId = cartlist[newIndex].brandId;
     }
     if (sub[i].num==0){
       sub[i].flag=false;
     }
   }
   var buycount = this.calintoCart(cartlist);
   this.setData({
     currentSubCategoryList:sub,
     cartList: cartlist,
     buyCount: buycount,
   })
   console.log(this.data.cartList)
   console.log('-------------------')
   console.log(this.data.currentSubCategoryList)
 },
  onLoad: function (options) {
    // if (getCurrentPages().length != 0) {
    //   //刷新当前页面的数据
    //   getCurrentPages()[getCurrentPages().length - 1].onLoad()
    // }
    console.log("页面加载中。。。。")
    this.getCatalog();
    // this.getGoodsInfo();
  },
 onReady: function() {
  // 页面渲染完成
  
 },
 onShow: function() {
  // 页面显示
  //  this.getCatalog();
   this.dealDataOfCart();
   this.refreshShop();
 },
 onHide: function() {
  // 页面隐藏
 },
 onUnload: function() {
  // 页面关闭
 }
})